﻿@using Newtouch.Infrastructure
@{
    ViewBag.Title = "RehabPrescription";
    Layout = null;
    //康复处方是否引用治疗建议
    var isWithRehabSuggestion = SysConfigReader.Bool("IS_WithRehabSuggestion", false).Value;
}
<div id="linkkfcf" role="tabpanel" class="tab-pane" style="width:96.5%; float:right; margin-right: 10px; border:solid 1px #ddd; margin-top: 3px;">
    <div class="contentPanel">
        <div style="background-color: #fff;">
            <table id="gridkfcf"></table>
            <div id="gridkfcfPager"></div>
        </div>
    </div>
    <div id="bottom" class="clearfix" style="border-top: solid 1px #ddd; height: 80px;margin-bottom:1px;">
        <table class="form" id="tableRehabPresAmount" style="float:left; width:50%;border-right: solid 1px #ddd;"></table>
        <div class="lowerrightcorner" style="margin-left: 50%;width: 50%;height: 100%;">
            <table class="form" style="position: relative; top: 25%;">
                <tr>
                    <th class="formTitle">总金额：</th>
                    <td class="formValue" id="tdRehabTotalAmount"></td>
                    <td style="width: 90px;"></td>
                    <td></td>
                </tr>
                <tr>
                    <td class="formValue">
                        @if (isWithRehabSuggestion)
                        {
                            <input type="button" class="btn btn-success" value="康复建议" style="margin-left:48%; " onclick="AddRefeKfjy()" />
                        }
                    </td>
                    <td class="formValue">
                        <input type="button" class="btn btn-primary" value="返回病历" style="margin-left:48%; display:table-cell" onclick="SaveRehabPres()" />
                    </td>
                    <td class="formValue">
                        <input type="button" class="btn btn-primary" value="另存为模板" style="display:table-cell;" onclick="saveAsRehabTemplate()" />
                    </td>
                    <td class="formValue">
                        <input type="button" class="btn btn-primary" value="F3：保存处方" style="display:table-cell;" onclick="SaveRehabPres('1')" />
                    </td>
                </tr>
            </table>
        </div>
    </div>
</div>

@*康复处方*@
<script>
    var kfcfflag = 0;
    var kflocaldata = new Array();

    function init_RehabPrescription() {

        //仅尚未保存到数据库的处方需要初始化在grid中
        kflocaldata = new Array();
        if (window.alldataArray.kfcf) {
            kflocaldata = $.jsonWhere($.deepClone.clone(window.alldataArray.kfcf), function(icf){
                return !!!icf.cfId;
            });
            $.each(kflocaldata, function () {
                if(!this.cfh){
                    alert('处方异常');
                    location.href = location.href;
                }
                this.action = getRehbActionStr()
            });
        }
        else{
            window.alldataArray.kfcf = new Array(); //方便后面使用$.each()
        }

        if (kfcfflag == 0) {   //该页面初始化
            gridkfcf();
            kfcfflag = 1;
        }
        else {
            $("#gridkfcf").clearGridData(); //先清
            //再次打开该页面
            $("#gridkfcf").jqGrid('setGridParam', {
                datatype: 'local',
                data: kflocaldata
            }).trigger("reloadGrid");

            ////启用行内编辑
            //EnableRehabInlineEditBox();
        }

        //立刻触发编辑其中一个本次就诊的已提交处方（未提交到库中的肯定会在编辑列表中）
        var triggereditcfh = sessionStorage.getItem("triggereditcfh");
        if(!!triggereditcfh){
            sessionStorage.removeItem("triggereditcfh");
            $("#floatLeftMostPartDiv div[data-href='lscf']").trigger('click');
            //未提交到数据库的处方，这里length 0 也没问题
            $('span.bbit-tree-node-text[data-value="' + triggereditcfh + '"]').trigger('click');
        }
    }

    //处方列表
    function gridkfcf() {
        var $gridkfcf = $("#gridkfcf");
        $gridkfcf.jqGrid({
            datatype: 'local',
            data: kflocaldata,
            height: $(window).height() - 230,
            //altRows: true,//隔行换色
            shrinkToFit: true,   //true:按比例初始化列宽度 false:使用colModel指定的宽度
            autowidth: true,
            rownumbers: true,  //是否显示序号
            multiselect: true,
            editurl: "clientArray",  //行编辑不向服务器提交数据
            unwritten: false,
            colModel: [
                { label: 'cfId', name: 'cfId', hidden: true },
                { label: 'ybwym', name: 'ybwym', hidden: true },
                { label: 'xzsybz', name: 'xzsybz', hidden: true },
                { label: 'cfmxId', name: 'cfmxId', hidden: true },
                { label: '<span class="required">*</span>处方号', name: 'cfh', width: 180, align: 'center'},
                {
                    label: 'xmCode', name: 'xmCode', editwidth: '100%', align: 'center', editable: true, hidden: true
                },
                {
                    label: '<span class="required">*</span>项目名称', name: 'xmmc', width: 280, editwidth: '100%', align: 'center', editable: true
                },
                {
                    label: 'zxks', name: 'zxks', editwidth: '100%', align: 'center', editable: true, hidden: true
                },
                {
                    label: '<span class="required">*</span>执行科室', name: 'zxksmc', width: 180, editwidth: '100%', align: 'center', editable: true
                },
                {
                    label: '<span class="required">*</span>单价', name: 'dj', width: 80, editwidth: '100%', align: 'center', editable: true
                },
                { label: '<span class="required">*</span>单位', name: 'dw', width: 80, editwidth: '100%', align: 'center', editable: true },
                { label: 'dwjls', name: 'dwjls', width: 80, editwidth: '100%', align: 'center', editable: true, hidden: true },
                { label: 'jjcl', name: 'jjcl', width: 80, editwidth: '100%', align: 'center', editable: true, hidden: true },
                {
                    label: '<span class="required">*</span>每次治疗量', name: 'mczll', width: 110, editwidth: '100%', align: 'center', editable: true, editrules: { integer: true, minValue: 1 }, editoptions: {
                        dataEvents: [
                                {
                                    type: 'change',
                                    fn: function (e) {
                                        var cellval = $(this).val();
                                        if(cellval.replace(/(^\s*)|(\s*$)/g, "") == ""){
                                            $.modalAlert("每次治疗量为空，请确认。", 'warning');
                                            return;
                                        }
                                        if(isNaN(cellval)){
                                            $.modalAlert("每次治疗量：请填写数字", 'warning');
                                            $(this).val('')
                                            return;
                                        }
                                        var row = $(e.target).closest('tr.jqgrow');
                                        var rowid = row.attr('id');

                                        CalculateRehabEachLineSlAndJe(rowid);   //计算 明细总量、明细金额和处方金额
                                    }
                                }
                        ]
                    }
                },
                { label: '<span class="required">*</span>频次', name: 'pcmc', width: 80, editwidth: '100%', align: 'center', editable: true },
                { label: 'pcCode', name: 'pcCode', width: 100, editwidth: '100%', align: 'center', editable: true, hidden: true },
                {
                    label: '<span class="required">*</span>次数', name: 'sl', width: 80, editwidth: '100%', align: 'center', editable: true, editrules: { integer: true, minValue: 1 }, editoptions: {
                        dataEvents: [
                                {
                                    type: 'change',
                                    fn: function (e) {
                                        var cellval = $(this).val();
                                        if(cellval.replace(/(^\s*)|(\s*$)/g, "") == ""){
                                            $.modalAlert("数量为空，请确认。", 'warning');
                                            return;
                                        }
                                        if(isNaN(cellval)){
                                            $.modalAlert("数量：请填写数字", 'warning');
                                            $(this).val('')
                                            return;
                                        }
                                        var row = $(e.target).closest('tr.jqgrow');
                                        var rowid = row.attr('id');

                                        CalculateRehabEachLineSlAndJe(rowid);   //计算 明细总量、明细金额和处方金额
                                    }
                                }
                                //,
                                //{
                                //    type: 'keyup',
                                //    fn: function (e) {
                                //        var cellval = $(this).val();
                                //        if(cellval.replace(/(^\s*)|(\s*$)/g, "") == ""){
                                //            $.modalAlert("数量为空，请确认。", 'warning');
                                //            return;
                                //        }
                                //        if(isNaN(cellval)){
                                //            $.modalAlert("数量：请填写数字", 'warning');
                                //            $(this).val('')
                                //            return;
                                //        }
                                //        var row = $(e.target).closest('tr.jqgrow');
                                //        var rowid = row.attr('id');

                                //        CalculateRehabEachLineSlAndJe(rowid);   //计算 明细总量、明细金额和处方金额
                                //    }
                                //}
                        ]
                    }
                },
                { label: '部位', name: 'bw', width: 160, editwidth: '100%', align: "center", editable: true },
                {
                    label: '转自费', name: 'iszzf', width: 80, editwidth: '100%', align: 'center', edittype: "select", editable: true, editoptions: {
                        dataEvents: [
                            {
                                type: 'change',
                                fn: function (e) {
                                    var row = $(e.target).closest('tr.jqgrow');
                                    var rowid = row.attr('id');
                                    $("#" + rowid + "_zzfbz").val($(this).val());
                                }
                            }
                        ]

                    }
                },
                { label: 'zzfbz', name: 'zzfbz', editwidth: '', align: 'center', editable: true, hidden: true },
                { label: '<span class="required">*</span>总量', name: 'zl', width: 80, editwidth: '100%', align: 'center', editable: true },
                { label: '<span class="required">*</span>金额', name: 'je', width: 100, editwidth: '100%', align: 'center', editable: true },
                { label: '操作', name: 'action', width: 120, align: 'center' }
            ],
            editinputwidthborder: false,    //是否需要边框 默认为true
            editinputborderradius: false,   //是否需要边框圆角 默认true（有圆角）
            pager: "#gridkfcfPager",
            loadComplete: function () {
                ////自动触发新处方
                //if (kflocaldata && kflocaldata.length == 0) {
                //    newRehPresData();
                //}
            },
            gridComplete: function () {
                EnableRehabInlineEditBox();
            }
        });

        //二级菜单
        $gridkfcf.jqGrid('setGroupHeaders', {
            useColSpanStyle: true,
            groupHeaders: [
            {
                startColumnName: 'xmmc',
                numberOfColumns: 5,
                titleText: '基本信息'
            }, {
                startColumnName: 'mczll',
                numberOfColumns: 5,
                titleText: '项目用法'
            }]
        });

        //自定义按钮
        $gridkfcf
            .navGrid('#gridkfcfPager', { edit: false, add: false, del: false, search: false, refresh: false, view: false, position: "left", cloneToTop: false })
            .navButtonAdd('#gridkfcfPager', {
                buttonicon: "glyphicon glyphicon-remove",
                title: "删除明细",
                caption: "删除明细",
                position: "last",
                onClickButton: function () {
                    var selRowData = $("#gridkfcf").jqGrid('getRowData_AllLine', true);
                    if(selRowData.length == 0){
                        $.modalAlert("尚未选中任何明细", 'warning');
                        return;
                    }
                    else{
                        $.each(selRowData, function () {   //1.删除行
                            deleteRehRowData(this.jqRowId, false);
                        });
                        CalculateRehabPresAmount();  //2.计算处方的金额
                    }
                },
            })
            .navSeparatorAdd("#gridkfcfPager", { sepclass: "ui-separator", sepcontent: '' })
            .navButtonAdd('#gridkfcfPager', {
                buttonicon: "glyphicon glyphicon-new-window",
                title: "新处方",
                caption: "新处方",
                position: "last",
                onClickButton: function () {
                    newRehPresData();
                },
            });
    }

    //启用行内编辑
    function EnableRehabInlineEditBox(){
        var ids = $("#gridkfcf").getDataIDs();
        $.each(ids, function () {
            //打开编辑模式
            $("#gridkfcf").jqGrid('editRow', String(this), false, initRehabInlineFunc);

            //标识处方颜色
            var cfh = $("#gridkfcf").getRowData(String(this)).cfh;
            var cfColor = getCfColor(@Html.Raw(((int)EnumCflx.RehabPres).ToString()),cfh);
            $('#gridkfcf tr[id="' +  String(this) + '"]').css('border-left-color',cfColor);
            $('#gridkfcf tr[id="' +  String(this) + '"]').css('border-left-style','solid');
            $('#gridkfcf tr[id="' +  String(this) + '"]').css('border-left-width','5px');

            CalculateRehabEachLineSlAndJe(String(this), false);
        });

        CalculateRehabPresAmount();  //计算处方的金额
    }

    //初始化 浮层
    function initRehabInlineFunc(rowid) {
        //部分列只读
        $("#" + rowid + "_dj").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_dw").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_pcmc").attr('readonly','true');
        $("#" + rowid + "_zl").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_je").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_xmmc").attr('autocomplete', 'off'); 
        $("#" + rowid + "_zxksmc").attr('autocomplete', 'off'); 
        $("#" + rowid + "_bw").parent().next().children('select').html('');
        $("#" + rowid + "_bw").parent().next().children('select').append('<option value="1">是</option><option value="0">否</option>');

        var iszzfval = $("#" + rowid + "_zzfbz").val();
        if (!!iszzfval) {
            $("#" + rowid + "_bw").parent().next().children('select').val(iszzfval).trigger("change");
        } else {
            $("#" + rowid + "_bw").parent().next().children('select').val(0).trigger("change");
        }

        var currlineCfh = $("#gridkfcf").getRowData(rowid).cfh;
        //项目浮层
        $("#" + rowid + "_xmmc").sfxmFloatingSelector({
            djDecimalPlaces: 4,
            searchType : 'sfxm.dwjls',
            ajaxparameters: function ($thisinput) {
                var flag = false;
                //限制用药的话，flag=true
                if (window.currPatientInfo.brxzCode != "" &&'@ViewBag.ControlbrxzCode'.indexOf(window.currPatientInfo.brxzCode) > -1) {
                    flag = true;
                };
                return "onlyybflag=" + flag + "&mzzybz=1&dllb=2&sfdllx=Rehab&keyword=" + $.trim($thisinput.val());
            },
            itemdbclickhandler: function ($this) {
                //检查重复
                var isRepeatedAdd = false;
                var addxmCode = $this.attr('data-sfxmCode');
                $.each($("#gridkfcf").getDataIDs(), function () {
                    var cfh = $("#gridkfcf").getRowData(String(this)).cfh;
                    var xmCode = $('#' + $($("#gridkfcf").getRowData(String(this)).xmCode).attr('id')).val();
                    if (addxmCode == xmCode && String(this) != rowid && cfh == currlineCfh) {
                        isRepeatedAdd = true;
                        return;
                    }
                });
                if (isRepeatedAdd) {
                    $.modalAlert("单张处方下明细不能重复", 'warning');
                    return;
                }

                $("#" + rowid + "_xmmc").val($this.attr('data-sfxmmc'))
                $("#" + rowid + "_xmCode").val($this.attr('data-sfxmCode'))
                $("#" + rowid + "_dwjls").val($this.attr('data-dwjls'))
                $("#" + rowid + "_jjcl").val($this.attr('data-jjcl'));
                $("#" + rowid + "_dj").val($this.attr('data-dj'));
                $("#" + rowid + "_dw").val($this.attr('data-dw'));
                $("#" + rowid + "_zxks").val($this.attr('data-zxks'));
                $("#" + rowid + "_zxksmc").val($this.attr('data-zxksmc'));
                //初始化为1
                $("#" + rowid + "_mczll").val($this.attr('data-dwjls'));
                $("#" + rowid + "_sl").val(1);
                $("#" + rowid + "_xmmc").css('background-color','#f6f7fb').attr('readonly','true');
                CalculateRehabEachLineSlAndJe(rowid);   //计算 明细总量、明细金额和处方金额
            },
        });
        //执行科室浮层
        //$("#" + rowid + "_zxksmc").ksFloatingSelector({
        //    itemdbclickhandler: function ($this) {
        //        $("#" + rowid + "_zxks").val($this.attr('data-Code'))
        //        $("#" + rowid + "_zxksmc").val($this.attr('data-Name'))
        //    },
        //});
        $("#" + rowid + "_zxksmc").newtouchBatchFloatingSelector({
            height: 170,
            width: 300,
            caption: "选择科室",
            url: '/Prescription/GetSfxmZxksSelectJson',
            clickautotrigger: true,
            ajaxparameters: function ($thisinput) {
                return 'sfxmCode=' + $("#" + rowid + "_xmCode").val() + "&keyword=" + $thisinput.val();
            },
            colModel: [
                { label: '编号', name: 'Code', widthratio: 40 },
                { label: '名称', name: 'Name', widthratio: 60 },
                { label: '拼音', name: 'py', hidden: true }
            ],
            itemdbclickhandler: function ($thistr) {
                $("#" + rowid + "_zxks").val($thistr.find("td:eq(0)").html());
                $("#" + rowid + "_zxksmc").val($thistr.find('td:eq(1)').html());
                return;
            },
        });
        //频次浮层
        $("#" + rowid + "_pcmc").pcFloatingSelector({
            showtext: 'yzpcmc',
            attrcols: ['yzpcmc', 'yzpcCode', 'zxcs', 'zxzq', 'zxzqdw'],
            checkItemActivity: checkItemActivity,
            itemdbclickhandler: function ($this) {
                $("#" + rowid + "_pcmc").val($this.attr('data-yzpcmc'));
                $("#" + rowid + "_pcCode").val($this.attr('data-yzpcCode'));
            },
        });

        //部位浮层
        $("#" + rowid + "_bw").bwFloatingSelector({
            showtext: 'bwmc',
            attrcols: ['bwmc', 'bwCode'],
            checkItemActivity: checkItemActivity,
            itemdbclickhandler: function ($this) {
                var mcval = "";
                if (typeof ($this) !== "undefined") {
                    $.each($this, function () {
                        mcval += this.attr('data-bwmc') + ",";

                    });
                    if (mcval.length > 0) {
                        mcval = mcval.substring(0, mcval.length - 1);
                    };
                }
                $("#" + rowid + "_bw").val(mcval);
            },
        });
    }

    //计算明细里的数量和金额
    function CalculateRehabEachLineSlAndJe(rowid, recalc) {
        var obj = new Object();

        obj.currRowZl = 0;  //初始值   //总计费数量
        obj.currRowZe = 0.00;  //初始值

        var currRowZll = $('#' + rowid + '_mczll').val();
        var currRowDwjls = $('#' + rowid + '_dwjls').val();
        var currRowSl = $('#' + rowid + '_sl').val();

        var currRowDj = $('#' + rowid + '_dj').val();

        if (parseFloat(currRowZll) > 0 && parseFloat(currRowDwjls) > 0 && parseFloat(currRowSl) > 0) {
            //治疗量 单位计数量 数量 不为空
            if(parseInt(currRowZll) < parseInt(currRowDwjls)){
                $.modalAlert('每次治疗量不能小于单位计量数', 'error');
                $('#' + rowid + '_mczll').val('');
                return;
            }
            obj.currRowZl = parseInt(parseInt(currRowZll) / parseInt(currRowDwjls)) * parseFloat(currRowSl);
        }
        if (obj.currRowZl && obj.currRowZl > 0 && currRowDj) {
            obj.currRowZe = roundingBy4she6ru5chengshuang(parseFloat(obj.currRowZl) * parseFloat(currRowDj),2);
        }

        $('#' + rowid + '_zl').val(obj.currRowZl);  //赋值
        $('#' + rowid + '_je').val(obj.currRowZe)   //赋值

        if(!(recalc === false)){
            CalculateRehabPresAmount()  //计算处方金额
        }
    }

    //计算处方金额
    function CalculateRehabPresAmount() {
        var presClassificationArr = new Array();   //处方分类
        var allData = $("#gridkfcf").jqGrid('getRowData_AllLine', null, true);
        $.each(allData, function () {
            var cfh = this.cfh;
            var rowid = this.jqRowId;

            var xmmc = $("#" + rowid + "_xmmc").val();
            var mczll = $("#" + rowid + "_mczll").val();
            var dwjls = $("#" + rowid + "_dwjls").val();
            var sl = $("#" + rowid + "_sl").val();
            var dj = $("#" + rowid + "_dj").val();

            if (!xmmc && !mczll && !dwjls && !sl && !dj) {
                return;
            }
            var cfje = roundingBy4she6ru5chengshuang(((parseFloat($.undefinedwith0(mczll)) / parseFloat($.undefinedwith0(dwjls))) * parseFloat($.undefinedwith0(sl)) * parseFloat($.undefinedwith0(dj))), 2);   //计算这个处方的金额

            var existPres = $.jsonWhere(presClassificationArr, function (v) {
                return v && v.cfh == cfh;    //相同处方 放到一个数组中  处方号为key 金额为value
            });
            if (existPres && existPres.length == 1) {       //已存在处方号
                existPres[0].cfje = roundingBy4she6ru5chengshuang((parseFloat(existPres[0].cfje) + parseFloat(cfje)), 2);
            } else {
                presClassificationArr.push({ cfh: cfh, cfje: cfje });    //新处方号
            }
        });

        var totalAmount = 0.00;
        //拼接html
        $('#tableRehabPresAmount').html('');   //先清空
        for (var i = 0; i < presClassificationArr.length; i++) {
            totalAmount = roundingBy4she6ru5chengshuang((parseFloat(totalAmount) + parseFloat(presClassificationArr[i].cfje)), 2);  //计算总金额
            $('#tableRehabPresAmount').append('<tr><th class="formTitle">处方号：</th><td class="formValue"><label style="color:red;">' + presClassificationArr[i].cfh + '</label></td><th class="formTitle">金额：</th><td class="formValue"><label style="color:red;">￥' + presClassificationArr[i].cfje + '</label></td></tr>');
        }
        $('#tdRehabTotalAmount').html('');  //先清空
        $('#tdRehabTotalAmount').append('<label style="color:red;">￥' + totalAmount + '</label>');
    }

    //新处方 按钮
    function newRehPresData() {
        var eRowIds = $("#gridkfcf").jqGrid("getDataIDs");
        if(eRowIds && eRowIds.length){
            $.modalConfirm("确定要添加新处方么？", function (flag) {
                if(flag){
                    newRehPresData_sub();
                }
            });
        }
        else{
            newRehPresData_sub();
        }
    }

    function newRehPresData_sub(){
        var dataRow = {
            cfId: null, //尚未保存到数据库
            cfh: GetNewPresNo(),
            ybwym:GetGuid(19,62),
            pcmc:'@(ViewBag.RehabItemDefaultFrequencyName)',
            pcCode:'@(ViewBag.RehabItemDefaultFrequencyCode)',
            action: getRehbActionStr()
        };
        $("#gridkfcf").jqGrid("addRowData", undefined, dataRow, "last");
        var rowIds = $("#gridkfcf").jqGrid('getDataIDs');
        $("#"+rowIds[rowIds.length-1]+"_xmmc").focus();
    }

    //新增明细
    function addRehRowData(selRowId) {
        //获取当前添加的处方号
        var selRowData = $("#gridkfcf").getRowData(selRowId);

        //新加一行
        var dataRow = {
            cfId: selRowData.cfId,  //同样cfId也要
            cfh: selRowData.cfh,
            ybwym:GetGuid(19,62),
            pcmc:'@(ViewBag.RehabItemDefaultFrequencyName)',
            pcCode:'@(ViewBag.RehabItemDefaultFrequencyCode)',
            action: getRehbActionStr()
        };
        $("#gridkfcf").jqGrid("addRowData", undefined, dataRow, "after", selRowId);
    }

    //删除明细
    function deleteRehRowData(selRowId, recalc) {
        if (!!selRowId) {
            delSqtx("kfcf",selRowId);
            $("#gridkfcf").jqGrid("delRowData", selRowId);
            if(!(recalc === false)){
                CalculateRehabPresAmount();
            }
        }
    }

    function getRehbActionStr() {
        return "<i class='fa fa-plus-square-o' style='font-size: large; color: #09a3ea;' onclick='addRehRowData($(this).parent().parent().attr(\"id\"));return false;'></i>&nbsp;&nbsp;&nbsp;<i class='fa fa-minus-square-o' style='font-size: large; color: #09a3ea;' onclick='deleteRehRowData($(this).parent().parent().attr(\"id\"));return false;'></i>";
    }

    //保存
    function SaveRehabPres(savetodb, justUpdateAlldataArray) {
        //获取所有行Id，遍历使编辑框处于保存状态
        var rowIds = $("#gridkfcf").jqGrid('getDataIDs');
        for (var i = 0; i < rowIds.length; i++) {
            var saveResult = $("#gridkfcf").saveRow(rowIds[i], null, null, null, function (callbackRowId) { }, null, null);

            if (!saveResult) {
                EnableRehabInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                return;   //保存失败，则return
            }
        }

        var gridkfcfData = $("#gridkfcf").jqGrid('getRowData_AllLine', null, true);
        var flag = false;
        if (savetodb == '1') {
            $.each(gridkfcfData, function () {
                var slval = this.sl;
                var mczllval = this.mczll;
                if (slval.replace(/(^\s*)|(\s*$)/g, "") == "" || mczllval.replace(/(^\s*)|(\s*$)/g, "") == "") {
                    $.modalAlert("数量或每次治疗量不能为空，请确认。", 'warning');
                    flag = true;
                    return false;
                } else if (this.xmmc == undefined || this.xmmc == "") {
                    $.modalAlert("缺少项目", "warning");
                    flag = true;
                    return false;
                }else if(this.zxksmc==undefined||this.zxksmc==""){
                    $.modalAlert("缺少执行科室", "warning");
                    flag = true;
                    return false;
                }else if (isNaN(this.dj) || this.dj == "") {
                    $.modalAlert("缺少单价", "warning");
                    flag = true;
                    return false;
                } else if (this.dw === undefined || this.dw == "") {
                    $.modalAlert("缺少单位", "warning");
                    flag = true;
                    return false;
                } else if (isNaN(this.sl) || this.sl == "") {
                    $.modalAlert("缺少数量", "warning");
                    flag = true;
                    return false;
                } else if (this.pcCode === undefined || this.pcCode == "" || this.pcmc === undefined || this.pcmc == "") {
                    $.modalAlert("缺少频次", "warning");
                    flag = true;
                    return false;
                }
            })
        }

        if (flag) {
            EnableRehabInlineEditBox();
            return;
        }
        $.each(gridkfcfData, function () {
            delete this.action;   //去掉action
            delete this.jqRowId;   //去掉jqRowId

            this.sfbz = false;  //一定是未收费才能进入编辑状态
            var thismxCfId = this.cfId;
            var matchedHisCf = $.jsonWhere(window.alldataArray.kfcf, function(icfmx){
                return !!icfmx.cfId && icfmx.cfId == thismxCfId;
            });
            if(matchedHisCf && matchedHisCf.length){
                this.cfzhdysj = matchedHisCf[0].cfzhdysj;
                this.zldzhdysj = matchedHisCf[0].zldzhdysj;
                this.sendtohisResult = matchedHisCf[0].sendtohisResult;
                this.klrq = matchedHisCf[0].klrq;
            }
        });
        //保存数据
        window.alldataArray.kfcf = $.jsonWhere(window.alldataArray.kfcf, function(icfmx){
            if(!!!icfmx.cfId){
                return false;   //编辑列表里有
            }
            for(var iIndex = 0; iIndex < gridkfcfData.length; iIndex++){
                if(gridkfcfData[iIndex].cfh == icfmx.cfh){
                    return false;
                }
            }
            return true;
        });

        $.each(gridkfcfData, function(){
            window.alldataArray.kfcf.push(this);
        });

       
        kflocaldata = new Array();
        if(!(justUpdateAlldataArray == true)){
            if (savetodb == '1') {
                if (SaveData(false, function () {
                    window.initHistoryPresTree('@Html.Raw(((int)EnumCflx.RehabPres).ToString())');

                    $.modalAlert("保存成功", 'success');
                })) {
                    $("#gridkfcf").clearGridData();
                } else {
                    EnableRehabInlineEditBox();
                }
            }
            else{
                //跳回病历页
                $('#myTab [href="#linkbl"]').trigger('click'); //初始化显示哪个tab
                //病例页重新加载处方，处方数据发生了变更
                triggleActive();
            }
        }
        else {
            triggleActive();
        }
    }

    //另存为模板
    function saveAsRehabTemplate(){
        $.modalOpen({
            id: "Form",
            title: "存为模板",
            url: "/MedicalRecord/Form",
            width: "400px",
            height: "250px",
            callBack: function (iframeId) {
                var mbObj = top.frames[iframeId].submitForm();
                if (!(mbObj && mbObj.mbmc && mbObj.mblx)) {
                    return;
                }
                $.modalClose("Form");
                //模板表
                var mbObj = {
                    mblx: mbObj.mblx,
                    cflx: @Html.Raw(((int)EnumCflx.RehabPres).ToString()),
                    mbmc: mbObj.mbmc,
                }
                //获取所有行Id，遍历使编辑框处于保存状态
                var rowIds = $("#gridkfcf").jqGrid('getDataIDs');
                for (var i = 0; i < rowIds.length; i++) {
                    var saveResult = $("#gridkfcf").saveRow(rowIds[i], null, null, null, function (callbackRowId) { }, null, null);

                    if (!saveResult) {
                        EnableRehabInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                        return;   //保存失败，则return
                    }
                }
                var gridkfcfData = $("#gridkfcf").jqGrid('getRowData_AllLine', null, true);
                if(!gridkfcfData || gridkfcfData.length==0){
                    EnableRehabInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                    $.modalAlert("模板明细不能为空", 'warning');
                    return;
                }

                $.each(gridkfcfData, function () {    //去掉action
                    for (var i = 0; i < $(this).length; i++) {
                        delete $(this)[i].action;
                    }
                });

                $.najax({
                    url: "/TemplateManage/PresTemplate/SaveData",
                    dataType: "json",
                    data: { mbObj: mbObj, mxList: gridkfcfData },
                    type: "POST",
                    success: function (data) {
                        $.modalAlert("保存成功", 'warning');
                        window.$('#current').trigger('click');
                    },
                    complete:function(){
                        EnableRehabInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                    }
                });
            }
        });
    }

    function AddRefeKfjy() {
        $.modalOpen({
            id: "AddKfjyForm",
            title: "康复建议",
            //brlx 1 门诊
            url: "/Prescription/AddKfjyForm?brlx=" + "1" + "&mzzyh=" + window.currPatientInfo.mzh,
            width: "900px",
            height: "450px",
            callBack: function (iframeId) {
                top.frames[iframeId].AcceptClick(function (zljyList) {
                    var addRefeResult = new Array();
                    if(zljyList && zljyList.length){
                        $.each(zljyList, function(){
                            var cfItem = {
                                xmCode : this.sfxmCode,
                                xmmc : this.sfxmmc,
                                zxks : this.zxks,
                                zxksmc : this.zxksmc,
                                dj : this.dj,
                                dw : this.dw,
                                dwjls : this.dwjls,
                                jjcl : this.jjcl,
                                mczll : this.mczll,
                                pcmc : this.pcmc,
                                pcCode : this.pc,
                                sl :parseInt(this.sl/this.mczll),
                                bw : this.bw,
                            };
                            var result = AddRehabCfmx(cfItem);
                            addRefeResult.push({jyId:this.jyId, result:result});
                        });
                    }
                    return addRefeResult;
                });
            }
        });
    }

    //康复处方明细，添加引用
    function AddRehabCfmx(cfItem, zhuijiaornew){
        var cfId;
        var cfh;
        //cfItem:xmCode xmmc zxks zxksmc dj dw dwjls jjcl mczll pcmc pcCode sl bw
        if(zhuijiaornew === 'new'){
            cfId = null;
            cfh = GetNewPresNo();
        }
        else{
            //向最后一张处方追加明细
            var allRowID = $("#gridkfcf").jqGrid('getDataIDs');
            var lastrowid = allRowID[allRowID.length - 1];
            var lastRowData = $("#gridkfcf").getRowData(lastrowid);  //获取最后一行的数据
            if (!!lastRowData && !!lastRowData.cfh) {
                //将明细追加到最后一张处方
                cfId = lastRowData.cfId;
                cfh = lastRowData.cfh;
            }
            else{
                //视为新处方
                cfId = null;
                cfh = GetNewPresNo();
            }
        }

        if(!(!!cfh && cfItem.xmCode && cfItem.xmmc && cfItem.dj && cfItem.dw
            && cfItem.dwjls && cfItem.jjcl && cfItem.mczll
            && cfItem.mczll >= cfItem.dwjls
            && cfItem.pcmc && cfItem.pcCode && cfItem.sl)){
            $.modalAlert("引用记录数据不完整（自动跳过）", 'warning');
            return false;
        }
        cfItem.cfh = cfh;
        cfItem.cfId = cfId;
        //检查重复
        var isRepeatedAdd = false;
        $.each($("#gridkfcf").getDataIDs(), function () {
            if (!isRepeatedAdd) {
                var xmCode = $('#' + $($("#gridkfcf").getRowData(String(this)).xmCode).attr('id')).val();
                var cfh = $("#gridkfcf").getRowData(String(this)).cfh;
                if (cfItem.xmCode == xmCode && cfItem.cfh == cfh) {
                    isRepeatedAdd = true;
                    return;
                }
            }
        });
        if (isRepeatedAdd) {
            $.modalAlert("单张处方下明细不能重复（自动跳过）", 'warning');
            return false;
        }
        else {
            cfItem.action = getRehbActionStr();
            cfItem.zl = cfItem.mczll * cfItem.sl;
            cfItem.je = parseFloat(cfItem.dj * (parseInt(cfItem.mczll / cfItem.dwjls) * cfItem.sl)).toFixed(2);
            $("#gridkfcf").jqGrid("addRowData", undefined, cfItem, "last");
            return true;
        }
    }

</script>